/************************************************************************
VARIABLES GLOBALES
************************************************************************/

// En milisegundos, intervalo de tiempo sobre el que se lanzan las peticiones de jsGetCallSessionInformation
var loop_jsGetCallSessionInformation_time=5000;
var getCallSessionInformationPollingId = null;

var loop_jsGetUserPresence_time=5000;
var getUserPresencePollingId = null;

var presence_state="undefined";
var seconds=0;
var countdownId;
var identificador;

var msg_preffix="in";

var primeravez=0;

/************************************************************************
************************************************************************/

// jsGetCallSessionInformation

var GetCallSessionInformation = Class.create();

GetCallSessionInformation.prototype = {
	initialize : function() {
	    this.data=null;
	    this.ajax=null;
		return;
	},
	load: function(param, target, args) {
	    this.ajax = new Ajax.Request("getCallSessionInformation.jsp",
              {
                method:'get', parameters: param,
                onSuccess: function(resp){
                var response = resp.responseText.replace(/\r|\n|\r\n/g, "");
                args.data=eval( '(' + response + ')' );
                target(args);
                },
                onFailure: function(resp)   { 
                },
                onException: function(resp) {
                }
              });
	}
}

function jsGetCallSessionInformation_writedata(args) {		
	//evaluate cause for end call 
	if( args.data[0].cause=="CallParticipantNoAnswer") cause="No Answer";
	else if( args.data[0].cause=="CallParticipantBusy") cause="Busy";
	else if( args.data[0].cause=="CallParticipantNotReachable") cause="Not Reachable";
	else if( args.data[0].cause=="CallParticipantHangUp") cause="Hung Up";
	else if( args.data[0].cause=="CallParticipantAborted") cause="Aborted";		  
	
	//if there isn't any error, show state in countdowncontainer.
        if (args.data[0].error==0){            
            if (args.data[0].status=="CallParticipantInitialConnecting") $('msgtext').innerHTML="Starting Call";
            else if (args.data[0].status=="CallParticipantInitialRinging") $('msgtext').innerHTML="Phone Ringing";
            else if (args.data[0].status=="CallParticipantConnected") $('msgtext').innerHTML="Call Established";
            else if (args.data[0].status=="CallParticipantTerminated"){
            		new Effect.Fade('terminar',{ queue: 'end'});
            		$('msgtext').innerHTML="Call Terminated<br>Duration:"+args.data[0].duration+"<br>Cause:"+cause;
		        clearInterval(getCallSessionInformationPollingId);
		        setTimeout ("cleanWindow()",15000);
            }            
        }
        //if there is an error, render "Servcie Temporally Unavailable"
        else if (args.data[0].error==1)
        {
             //hide endCall button, stop calling getCallSessionInformation(), show Error message and cleanWindow()
             new Effect.Fade('terminar', {queue: 'end'});
             render_error("Service Temporally Unavailable");  
             clearInterval(getUserPresencePollingId);
             setTimeout ("cleanWindow()",5000);       
        }
        return;
}

function jsGetCallSessionInformation()  {
actualizador=new GetCallSessionInformation();
var aleatorio = Math.random();
actualizador.load("callid="+identificador+"&param="+aleatorio, jsGetCallSessionInformation_writedata, {div:'contenedor'} );
}

function loop_jsGetCallSessionInformation()
{
jsGetCallSessionInformation();
getCallSessionInformationPollingId = setInterval("jsGetCallSessionInformation()",loop_jsGetCallSessionInformation_time);
}



/************************************************************************
************************************************************************/

// jsGetUserPresence

var GetUserPresence = Class.create();

GetUserPresence.prototype = {
	initialize : function() {
	    this.data=null;
	    this.ajax=null;
		return;
	},
	load: function(param, target, args) {
	    this.ajax = new Ajax.Request("getUserPresence.jsp",
              {
                method:'get', parameters: param,
                onSuccess: function(resp){
                var response = resp.responseText.replace(/\r|\n|\r\n/g, "");
                args.data=eval( '(' + response + ')' );
                target(args);
                },
                onFailure: function(resp)   { 
                },
                onException: function(resp) {
                }
              });
	}
}

function jsGetUserPresence_writedata(args) {		
	if(args.data[0].presence==1 && primeravez==0) {		  			  
		$('boton_llamada').enable();
		primeravez==1;
	}
		  			  		  			  
	if (args.data[0].error==0)
	{               
		//Si la linea esta ocupada, mostrar el div ocupado
		if ((args.data[0].presence==-1 && presence_state=="libre")){
			//console.log("cambiando de libre a ocupado");
			new Effect.Fade('img_presence_disponible');
			new Effect.Fade('presence_disponible');               
			new Effect.Fade('img_presence_disponible_deferred');               
			new Effect.Appear('img_presence_ocupado_deferred',{ queue: 'end' , duration: 0.5});
			new Effect.Appear('img_presence_ocupado',{ queue: 'end', duration: 0.5});
			new Effect.Appear('presence_ocupado',{ queue: 'end', duration: 0.5});
			presence_state="ocupada";			               
		}
		else if ((args.data[0].presence==-1 && presence_state=="undefined")){
			//console.log("cambiando de undefined a ocupado");               
			new Effect.Fade('img_presence_undefined');
			new Effect.Fade('presence_undefined');
			new Effect.Fade('img_presence_undefined_deferred'); 
			new Effect.Appear('img_presence_ocupado',{ queue: 'end', duration: 0.5});           
			new Effect.Appear('img_presence_ocupado_deferred',{ queue: 'end', duration: 0.5});
			presence_state="ocupada";			               
		}
		else if ((args.data[0].presence==1 && presence_state=="ocupada")){
			//console.log("cambiando de ocupado a libre");
			new Effect.Fade('img_presence_ocupado');
			new Effect.Fade('presence_ocupado');	
			new Effect.Fade('img_presence_ocupado_deferred');    		                              
			new Effect.Appear('img_presence_disponible',{ queue: 'end', duration: 0.5});
			new Effect.Appear('presence_disponible',{ queue: 'end', duration: 0.5});
			new Effect.Appear('img_presence_disponible_deferred',{ queue: 'end', duration: 0.5});
			presence_state="libre";			                       
		}
		else if ((args.data[0].presence==1 && presence_state=="undefined")){
			//console.log("cambiando de undefined a libre");
			new Effect.Fade('img_presence_undefined');               
			new Effect.Fade('presence_undefined');
			new Effect.Fade('img_presence_undefined_deferred'); 
			new Effect.Appear('img_presence_disponible',{ queue: 'end', duration: 0.5});
			new Effect.Appear('presence_disponible',{ queue: 'end', duration: 0.5});
			new Effect.Appear('img_presence_disponible_deferred',{ queue: 'end', duration: 0.5});
			presence_state="libre";			                       
		}
		else if ((args.data[0].presence==0 && presence_state=="libre")){
			//console.log("cambiando de libre a undefined");
			new Effect.Fade('img_presence_disponible');
			new Effect.Fade('presence_disponible');
			new Effect.Fade('img_presence_disponible_deferred');    
			new Effect.Appear('img_presence_undefined',{ queue: 'end', duration: 0.5});
			new Effect.Appear('presence_undefined',{ queue: 'end', duration: 0.5});
			new Effect.Appear('img_presence_undefined_deferred',{ queue: 'end', duration: 0.5});
			presence_state="undefined";
		}			            
		else if ((args.data[0].presence==0 && presence_state=="ocupada")){
			//console.log("cambiando de ocupado a undefined");
			new Effect.Fade('img_presence_ocupado');               
			new Effect.Fade('presence_ocupado');	
			new Effect.Fade('img_presence_ocupado_deferred');		               
			new Effect.Appear('img_presence_undefined',{ queue: 'end', duration: 0.5});
			new Effect.Appear('presence_undefined',{ queue: 'end', duration: 0.5});        
			new Effect.Appear('img_presence_undefined_deferred',{ queue: 'end', duration: 0.5});
			presence_state="undefined";
		}			            
	}
	else if (args.data[0].error==1)
	{			            
		if (presence_state="libre") {
			presence_state="undefined";					     	   
			new Effect.Fade('img_presence_disponible');    
			new Effect.Fade('presence_disponible');		
			new Effect.Fade('img_presence_disponible_deferred');                           
			new Effect.Appear('img_presence_undefined',{ queue: 'end', duration: 0.5});
			new Effect.Appear('presence_undefined',{ queue: 'end', duration: 0.5});
			new Effect.Appear('img_presence_undefined_deferred',{ queue: 'end', duration: 0.5});
		}
		if (presence_state="ocupada") {
			presence_state="libre";
			new Effect.Fade('img_presence_ocupado');
			new Effect.Fade('presence_ocupado');      
			new Effect.Fade('img_presence_ocupado_deferred');                         
			new Effect.Appear('img_presence_undefined',{ queue: 'end', duration: 0.5});
			new Effect.Appear('presence_undefined',{ queue: 'end', duration: 0.5});
			new Effect.Appear('img_presence_undefined_deferred',{ queue: 'end', duration: 0.5});
		}
	}
return;
}

function jsGetUserPresence(){
actualizador=new GetUserPresence();
var aleatorio = Math.random();
actualizador.load("pymeURI=sip:"+pymeURI+"&param="+aleatorio, jsGetUserPresence_writedata, {div:'contenedor'} );
}

function loop_jsGetUserPresence()
{
jsGetUserPresence();
getUserPresencePollingId = setInterval("jsGetUserPresence()",loop_jsGetUserPresence_time);
}

/************************************************************************
************************************************************************/

// jsmakeCall

var makeCallSession = Class.create();
makeCallSession.prototype = {
	initialize : function() {
	    this.data=null;
	    this.ajax=null;
		return;
	},
	load: function(param, target, args) {
	    this.ajax = new Ajax.Request("makeCallSession.jsp",
              {
                method:'get', parameters: param,
                onSuccess: function(resp){
                  var response = resp.responseText.replace(/\r|\n|\r\n/g, "");
                  args.data=eval( '(' + response + ')' );
                  target(args);
                },
                onFailure: function(resp)   { 
                },
                onException: function(resp) {
                }
              });
	}
}


function jsmakeCallSession_writedata(args) {
        
        //Hide div for direct or deferred call, depending on type of main panel displayed
	if (diferida==1 && diferida_en==1)new Effect.Fade('calldeferred',{ queue: 'end'});
	else new Effect.Fade('numtel',{ queue: 'end'});
        
	if (args.data[0].error==0)        
	{
		//recogemos el identificador de inicio de llamada            
		identificador = args.data[0].callid;
		
		//Hide state icon while call is in process
		hideAllPresenceIcons();
		
		//stop asking for getUserPresence and start asking for getCallSessionInformation
		clearInterval(getUserPresencePollingId);
		loop_jsGetCallSessionInformation();
		
		//show message Call in Progress and show button endCall
		new Effect.Appear('callinfo',{ queue: 'end'});
		$('countdowncontainer').innerHTML="Call In Progress...";
	}
        else if (args.data[0].error==1)
	{   
	   	//reder Error message
	   	render_error("Service temporally unavailable.<br>Please try again in a few minutes");
		
		//clear getUserPresence() and getCallSessionInformation() loops, wait 5 segs and return
		clearInterval(getCallSessionInformationPollingId);
	 	clearInterval(getUserPresencePollingId);
	 	setTimeout ("cleanWindow()",5000); 
	}
        return;
}



function jsmakeCallSession()  { 
$('boton_llamada').disable();
$('boton_llamada_deferred').disable();
$('boton_llamada').hide();
$('boton_llamada_deferred').hide();
$('loader').show();
$('loader_deferred').show();
llamada=new makeCallSession();
//Parar de preguntar presencia mientras se realiza la llamada 
var aleatorio = Math.random(); 
if (diferida==1 && diferida_en==1)llamada.load("userURI=sip:"+$('sipuri_d').value+"&pymeURI=sip:"+pymeURI+"&userDisplayName="+$('display_name_d').value+"&hideUserIdentity="+$('ocultarid_d').checked+"&param="+aleatorio, jsmakeCallSession_writedata, {div:'contenedor'} );
else llamada.load("userURI=sip:"+$('sipuri').value+"&pymeURI=sip:"+pymeURI+"&userDisplayName="+$('display_name').value+"&hideUserIdentity="+$('ocultarid').checked+"&param="+aleatorio, jsmakeCallSession_writedata, {div:'contenedor'} );
}


/************************************************************************
************************************************************************/

// jsmakeDeferredCallSession


var makeDeferredCallSession = Class.create();
makeDeferredCallSession.prototype = {
	initialize : function() {
	    this.data=null;
	    this.ajax=null;
		return;
	},
	load: function(param, target, args) {
	    this.ajax = new Ajax.Request("jsp/makeDeferredCallSession.jsp",
              {
                method:'get', parameters: param,
                onSuccess: function(resp){
                  var response = resp.responseText.replace(/\r|\n|\r\n/g, "");
                  args.data=eval( '(' + response + ')' );
                  target(args);
                },
                onFailure: function(resp)   { 
                },
                onException: function(resp) {
                }
              });
	}
}


function jsmakeDeferredCallSession_writedata(args) {
	
	//hide calldeferred div, render callinfo one
	new Effect.Fade('calldeferred',{ queue: 'end', duration: 1});
	new Effect.Appear('callinfo',{ queue: 'end'});
	
	if (args.data[0].error==0)        
	{
		//recogemos el identificador de inicio de llamada            
		identificador = args.data[0].callid;
		//start countdown for deferred.
		start_countdown();
	}
	else if (args.data[0].error==1)        
	{
		render_error("Service temporally unavailable.<br>Please try again in a few minutes");
	}
	
	return;
}

function jsmakeDeferredCallSession()  {

$('boton_llamada').disable();
$('boton_llamada_deferred').disable();
$('boton_llamada').hide();
$('boton_llamada_deferred').hide();
$('loader').show();
$('loader_deferred').show();

//clearInterval(getUserPresencePollingId);
llamada=new makeDeferredCallSession();
var aleatorio = Math.random(); 
tminutos=$('tdelay').value;
tmilisegundos= tminutos*60000;
llamada.load("userURI=sip:"+$('sipuri_d').value+"&pymeURI=sip:"+pymeURI+"&userDisplayName="+$('display_name_d').value+"&hideUserIdentity="+$('ocultarid_d').checked+"&delay="+tmilisegundos+"&param="+aleatorio, jsmakeDeferredCallSession_writedata, {div:'contenedor'} );
}




/************************************************************************
************************************************************************/

// jsendCall

var endCall = Class.create();
endCall.prototype = {
	initialize : function() {
	    this.data=null;
	    this.ajax=null;
		return;
	},
	load: function(param, target, args) {
	    this.ajax = new Ajax.Request("jsp/endCallSession.jsp",
              {
                method:'get', parameters: param,
                onSuccess: function(resp){
                  var response = resp.responseText.replace(/\r|\n|\r\n/g, "");
                  args.data=eval( '(' + response + ')' );
                  target(args);
                },
                onFailure: function(resp)   { 
                },
                onException: function(resp) {
                }
              });
	}
}


function jsendCall_writedata(args) {
              
	if (args.data[0].error==1)
	{    
		new Effect.Fade('terminar',{ queue: 'end'});
		render_error("Service Temporally Unavailable");
		//clear getUserPresence() and getCallSessionInformation() loops, wait 5 segs and return
		clearInterval(getCallSessionInformationPollingId);
	 	setTimeout ("cleanWindow()",5000); 
	}
	return;
}

function jsendCall()  {
llamada=new endCall();
var aleatorio = Math.random(); 
llamada.load("identificador="+identificador+"&param="+aleatorio, jsendCall_writedata, {div:'contenedor'} );
}




/***********************************************
*Funcion de inicialización
***********************************************/

function initWindow(){
$('boton_llamada').disable();   

if (diferida==1 && diferida_en==1){
	$('numtel').hide();
	$('calldeferred').show();
}
loop_jsGetUserPresence();
}


function cleanWindow(){
//set initial state
presence_state="undefined";
tminutos=$('tdelay').value=0;
identificador=null;
//Desabilitamos los loaders
$('loader').hide();
$('loader_deferred').hide();
//Mostramos los botones de llamar
$('boton_llamada').show();
$('boton_llamada_deferred').show();

//hide call infor panel
new Effect.Fade('callinfo',{ queue: 'end', duration: 1});	      		       

$('boton_llamada').disable();   
$('boton_llamada_deferred').enable();

//start getUserPresence() loop again
loop_jsGetUserPresence();

//show makeCall or makeCallDeferred
if (diferida==1 && diferida_en==1)new Effect.Appear('calldeferred',{ queue: 'end'});	 
else new Effect.Appear('numtel',{ queue: 'end'});

//Clean messages text
$('countdowncontainer').innerHTML="";
$('msgtext').innerHTML="";
${'aviso'}.innerHTML="";
}

/***********************************************
*Seleccion de metodo de llamada
***********************************************/
function render_error(msg){
	$('countdowncontainer').innerHTML="";
	$('msgtext').innerHTML="";
	${'aviso'}.innerHTML=msg;
}

function llamar(){
	if ($('tdelay').value==0){
		make_direct_call();
	}
	else{
		jsmakeDeferredCallSession();
	}
}

function make_direct_call(){
	if (presence_state=="ocupada"){
		//Hide div for direct or deferred call, depending on type of main panel displayed
		if (diferida==1 && diferida_en==1)new Effect.Fade('calldeferred',{ queue: 'end'});
		else new Effect.Fade('numtel',{ queue: 'end'});
		
		//show error notice, clear getUserPresence and restart after 5 segs
		$("aviso").innerHTML="All operators are busy, please try again in a few minutes";
		clearInterval(getUserPresencePollingId);
		setTimeout ("cleanWindow()",5000); 
	}
	else{
		jsmakeCall();
	}
}




/***********************************************
* Disable "Enter" key in Form script- By Nurul Fadilah(nurul@REMOVETHISvolmedia.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
/* FORMA DE USO: Introduces este evento en cada elemento del formulario onkeypress="return handleEnter(this, event)" */
                
function handleEnter (field, event) {
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keyCode == 13) {
			var i;
			for (i = 0; i < field.form.elements.length; i++)
				if (field == field.form.elements[i])
					break;
			i = (i + 1) % field.form.elements.length;
			field.form.elements[i].focus();
			return false;
		} 
		else
		return true;
}   


function hideAllPresenceIcons(){
	new Effect.Fade('presence_ocupado');
	new Effect.Fade('presence_disponible');
	new Effect.Fade('presence_undefined');
	new Effect.Fade('img_presence_ocupado');
	new Effect.Fade('img_presence_disponible');
	new Effect.Fade('img_presence_undefined');
	new Effect.Fade('img_presence_ocupado_deferred');
	new Effect.Fade('img_presence_disponible_deferred');
	new Effect.Fade('img_presence_undefined_deferred');
}


function start_countdown (){
minutes=$('tdelay').value;
seconds=minutes*60;
countdownId = setInterval("countdown_step()",1000);
}

function countdown_step()
{
	if (seconds>=0) $('countdowncontainer').innerHTML="There are "+seconds+" seconds till process your call";
	else {	
		//clean countdown message and fill msgtxt
		$('countdowncontainer').innerHTML="Call In Progress...";
		$('msgtxt').innerHTML="Querying presence availability for making the call...";
		
		//stop countdown and getUserPresence() loop
		clearInterval(idcuentatras);
		clearInterval(getUserPresencePollingId);
		//start asking for getCallSessionInformation
		loop_jsGetCallSessionInformation();	
		
		//hide all presence icons
		hideAllPresenceIcons();
	}
	seconds-=1;
}
